package com.penghaisoft.microwms.materialhand.web.outwarehouse.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.data.model.RawRequisitionSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.RawRequisitionDto;
import com.penghaisoft.microwms.common.dto.RawRequisitionMesDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.IMaterialRequisitionService;

import lombok.extern.slf4j.Slf4j;

/** 
* @ClassName: RawRequisitionController 
* @Description: 原材料返修出库任务
* @author jzh
* @date 2018年6月20日 下午4:39:54  
*/
@RestController
@RequestMapping(value = "raw/requisition")
@Slf4j
public class RawRequisitionController {
	@Autowired
    private IMaterialRequisitionService iMaterialRequisitionService;
	
	@Autowired
	private IMesInterfaceService mesInterfaceService;
	
	@Resource
	private MesProperties mesProperties;
	
	  /** 
	* @Title: queryRequisition 
	* @Description: 1.返修出库提单
	* @param @param rawRequisitionDto
	* @param @return  参数说明 
	* @return HandResp    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("queryrequisition")
	    public HandResp queryRequisition(@RequestBody RawRequisitionDto rawRequisitionDto){
	        HandResp result = new HandResp();
	        //Code先置为1SUCCESS
	        result.setCode(Constant.SUCCESS);
	        result.setMsg("可进行返修出库！");
	        if (rawRequisitionDto.getRequisitionNo()==null||rawRequisitionDto.getRequisitionNo().equals("")){
	            result.setCode(Constant.FAIL);
	            result.setMsg("请输入领料单号！");
	            return result;
	        }
	        //设置查询标志（RequisitionNo=？ ，ActiveFlag = 1,RequisitionType=1返修）
	        RawRequisition rawRequisition = new RawRequisition();
	        rawRequisition.setRequisitionNo(rawRequisitionDto.getRequisitionNo());
	        rawRequisition.setActiveFlag("1");
	        rawRequisition.setRequisitionType("1");//返修
	       
	        List<RawRequisition> tmp = iMaterialRequisitionService.queryRawRequisition(rawRequisition);
	        if(tmp.size() > 0){
	        	Boolean flag_all_2 = true;
	    		for (RawRequisition requisition : tmp){
	    			if(!"2".equals(requisition.getRequisitionStatus())){
						flag_all_2 = false;
					}
	    		}
	    		if(flag_all_2){
	    			result.setCode(Constant.FAIL);
	            	result.setMsg("全部发货完成！");
	    		}
	        }else{
	        	result.setCode(Constant.FAIL);
	        	result.setMsg("返修出库任务不存在！");
	        }
	        return result;
	    }
	  
	   /** 
		* @Title: queryRequisitionDetail 
		* @Description: 2.详细信息
		* @param @param rawRequisitionDto
		* @param @return  参数说明 
		* @return HandResp    返回类型
		* @author jzh 
		* @throws 
		*/
		@PostMapping("queryrequisitiondetail")
	    public HandResp queryRequisitionDetail(@RequestBody RawRequisitionDto rawRequisitionDto){
	        HandResp result = new HandResp();
	        //Code先置为1SUCCESS
	        result.setCode(Constant.SUCCESS);
	        if (rawRequisitionDto.getRequisitionNo()==null||rawRequisitionDto.getRequisitionNo().equals("")){
	            result.setCode(Constant.FAIL);
	            result.setMsg("请输入领料单号！");
	            return result;
	        }
	        //设置查询标志（RequisitionNo=？ ，ActiveFlag = 1,RequisitionType=1返修）
	        RawRequisition rawRequisition = new RawRequisition();
	        rawRequisition.setRequisitionNo(rawRequisitionDto.getRequisitionNo());
	        rawRequisition.setActiveFlag("1");
	        rawRequisition.setRequisitionType("1");//返修
	        //status不等于2
	        List<RawRequisition> tmp = iMaterialRequisitionService.queryRequisitionNot2(rawRequisition);
	        if(tmp.size() > 0){
	        	result.setList(tmp);
	        	result.setMsg("成功查询需出库信息！");
	        	
	        }else{
	        	result.setCode(Constant.FAIL);
	        	result.setMsg("返修信息不存在！");
	        }
	        
	        return result;
	    }

	
    /** 
    * @Title: requisitionScan 
    * @Description: 3.返修条码扫描
    * @param @param rawRequisitionDto
    * @param @return  参数说明 
    * @return HandResp    返回类型
    * @author jzh 
    * @throws 
    */
    @PostMapping("requisitionscan")
    public HandResp requisitionScan(@RequestBody RawRequisitionDto rawRequisitionDto){
        HandResp result = new HandResp();
        //入参条码barcode，loginName，领料单号requisitionNo
        String loginName = rawRequisitionDto.getLoginName();
        String barcode = rawRequisitionDto.getBarcode();
        String requisitionNo = rawRequisitionDto.getRequisitionNo();
        
        
        RawStorageSn rawStorageSn = new RawStorageSn();
        rawStorageSn.setBarcode(barcode);
        
        rawStorageSn.setActiveFlag("1");
        List<RawStorageSn> list = iMaterialRequisitionService.queryRawStorageSn(rawStorageSn);
        if(list.size()>0){
        	//查询状态为可用0，非冻结1出库2
            rawStorageSn.setBarcodeStatus("0");
            List<RawStorageSn> listStatus = iMaterialRequisitionService.queryRawStorageSn(rawStorageSn);
            if(listStatus.size() <= 0){
            	result.setCode(Constant.FAIL);
            	result.setMsg("此条码不可用,已出库或冻结!");
            }else{
            	//找到该条码对应的型号,长度
            	String model = list.get(0).getModel();
            	BigDecimal amount = list.get(0).getAmount() == null ? BigDecimal.ZERO : list.get(0).getAmount();
            	//出库单中对应型号
            	RawRequisition rawRequisition = new RawRequisition();
    	        rawRequisition.setRequisitionNo(rawRequisitionDto.getRequisitionNo());
    	        rawRequisition.setModel(model);
    	        rawRequisition.setActiveFlag("1");
    	        rawRequisition.setRequisitionType("1");//返修
    	        //需求数量大于实际数量，status不等于2
    	        List<RawRequisition> tmp = iMaterialRequisitionService.queryRequisitionDetail(rawRequisition);
    	        Date date = new Date();
            	if(tmp.size()>0){
            		for(RawRequisition tmpRequisition : tmp){
            			//需求数量
            			BigDecimal requireAmount = tmpRequisition.getRequireAmount() == null ? BigDecimal.ZERO : tmpRequisition.getRequireAmount();
            			BigDecimal realAmount = tmpRequisition.getRealAmount() == null ? BigDecimal.ZERO : tmpRequisition.getRealAmount();
                        
            			BigDecimal val = (realAmount.add(amount)).subtract(requireAmount);
                        int b = val.compareTo(Constant.RAW_MAX_STATIC_METER);
                        
                        if (realAmount.compareTo(requireAmount) == 0 || realAmount.compareTo(requireAmount) == 1) {
                        	result.setCode(Constant.FAIL);
                        	result.setMsg("此型号已扫描完成！");
                            return result;
                        } else if (b == 1) {
                        	result.setCode(Constant.FAIL);
                        	result.setMsg("该物料长度过长(实发数量只允许最多超过需求数量" + Constant.RAW_MAX_STATIC_METER + "米)!");
                            return result;
                        }
                        
                      //更改任务已分配数量为新数量，发货中
            			tmpRequisition.setRealAmount(amount);
            			tmpRequisition.setRequisitionStatus("1");//发货中
            			tmpRequisition.setGmtModified(date);
            			tmpRequisition.setLastModifiedBy(loginName);
            			//记录rawRequisitionSn
            			RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
            			rawRequisitionSn.setRequisitionId(tmpRequisition.getRequisitionId());
            			rawRequisitionSn.setPurchaseNo(tmpRequisition.getPurchaseNo());
            			rawRequisitionSn.setContractNo(tmpRequisition.getContractNo());
            			rawRequisitionSn.setRequisitionNo(tmpRequisition.getRequisitionNo());
            			rawRequisitionSn.setRequisitionType(tmpRequisition.getRequisitionType());
            			rawRequisitionSn.setBarcode(barcode);
            			rawRequisitionSn.setModel(model);
            			rawRequisitionSn.setModelDesc(tmpRequisition.getModelDesc());
            			rawRequisitionSn.setModelType(tmpRequisition.getModelType());
            			rawRequisitionSn.setAmount(amount);
            			rawRequisitionSn.setUnit(tmpRequisition.getUnit());
            			rawRequisitionSn.setGmtCreate(date);
            			rawRequisitionSn.setCreateBy(loginName);
            			rawRequisitionSn.setWaCode(list.get(0).getWaCode());
            			rawRequisitionSn.setWdCode(list.get(0).getWdCode());
            			rawRequisitionSn.setWhCode(list.get(0).getWhCode());
            			rawRequisitionSn.setWlCode(list.get(0).getWlCode());
            			rawRequisitionSn.setActiveFlag("1");
            			//更改条码状态为已出库
            			RawStorageSn newRawStorageSn = new RawStorageSn();
            			newRawStorageSn.setStorageSnId(list.get(0).getStorageSnId());
            			newRawStorageSn.setBarcodeStatus("2");
            			newRawStorageSn.setGmtModified(date);
            			newRawStorageSn.setLastModifiedBy(loginName);
            			
            			Resp resp = new Resp();
            			try{
                    		//更改任务已分配数量为新数量，发货中 并且 新增记录,更改条码状态为已出库（保证事物）
                    		resp = iMaterialRequisitionService.updateScanRequisition(tmpRequisition,rawRequisitionSn,newRawStorageSn);
                    		}catch(RuntimeException e){
                    			result.setCode("0");
                    			System.out.print(e.getMessage());
                    			result.setMsg(e.getMessage());
                    			return result;
                    		}
            			//成功
                		result.setCode(resp.getCode());
            			result.setList(list);
            			return result;
            		}	
            	}else{
            		result.setCode(Constant.FAIL);
                	result.setMsg("此条码型号在返修任务中不存在！");
            	}
            }	
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("此条码不存在！");
        }

        return result;
    }
    
    /** 
     * @Title: requisitionsConfig 
     * @Description: 最终确认
     * @param @param rawRequisitionDto
     * @param @return  参数说明 
     * @return HandResp    返回类型
     * @author jzh 
     * @throws 
     */
    @PostMapping("requisitionsconfig")
    public HandResp requisitionsConfig(@RequestBody RawRequisitionDto rawRequisitionDto){
        HandResp result = new HandResp();
        //Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        //loginName，领料单号requisitionNo
        String loginName = rawRequisitionDto.getLoginName();
      
        String requisitionNo = rawRequisitionDto.getRequisitionNo();
        
        RawRequisition rawRequisition = new RawRequisition();
        rawRequisition.setRequisitionNo(requisitionNo);
        
        rawRequisition.setActiveFlag("1");
        rawRequisition.setRequisitionType("1");//返修
        //需求数量大于实际数量，status不等于2
        List<RawRequisition> tmp = iMaterialRequisitionService.queryRequisitionDetail(rawRequisition);
    	if(tmp.size()>0){
    		for(RawRequisition tmpRequisition : tmp){
    			
    			String model = tmpRequisition.getModel();
    			result.setCode("0");
        		result.setMsg("该返修任务下型号"+model+"未扫描完！");
        		return result;
    		}
    	}
    	
        String url = mesProperties.getUrl() + "/imes-provider/productplan/follow/ordersplit/materialin";
        
        RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
        rawRequisitionSn.setRequisitionNo(requisitionNo);
        List<RawRequisitionSn> list = iMaterialRequisitionService.queryMesRepairList(rawRequisitionSn);
        
        List<RawRequisitionMesDto> mesList = new ArrayList<RawRequisitionMesDto>();
        for(RawRequisitionSn snTmp : list){
        	RawRequisitionMesDto mesOb = new RawRequisitionMesDto();
        	mesOb.setMaterialId(snTmp.getBarcode());
        	mesOb.setMaterialCode(snTmp.getModel());
        	mesOb.setMaterialType(snTmp.getModelType());
        	mesOb.setQuantity(snTmp.getAmount());
        	mesOb.setMeasureUnit(snTmp.getUnit());
        	mesList.add(mesOb);
        }
        
        JSONObject ob = new JSONObject();
        ob.put("receiptNo", requisitionNo);
        ob.put("materialList", mesList);
//      领料类型 1 普通料（钢管、pe管、管件） 2 辅料
		ob.put("type", "1");
//		调mes新增接口
        HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, ob.toJSONString());
//        返回码，0：失败，1：成功
		if(handResp.getCode() != null && handResp.getCode().equals("0")){
			result.setCode(handResp.getCode());
			result.setMsg(handResp.getMsg());
	        return result;
		}else{
			//将返修单置为已发货2
	    	Resp resp = new Resp();
	    	rawRequisition.setRequisitionStatus("2");//发货完成
	    	rawRequisition.setLastModifiedBy(loginName);
	    	rawRequisition.setGmtModified(new Date());
//	    	0未传给MES;1 已传MES;2 MES确认
	    	rawRequisition.setMesFlag("1");
	    	rawRequisition.setMesMsg("code:" + handResp.getCode() + " message:" + handResp.getMsg());
	    	resp = iMaterialRequisitionService.updateRequisition(rawRequisition);
	        result.setCode(resp.getCode());
	        if(resp.getMsg()!= null){
	        	result.setMsg(resp.getMsg());
	        }else{
	        	result.setMsg("返修出库成功！");
	        }
		}
		
        return result;
    }
    
    
}
